import { defineStore } from 'pinia'
import { ref} from 'vue'

export const useMembersStore = defineStore('members',() => {
    // 模拟会员数据
    let members = ref([
        {
            id: 1,
            memberName: "张三",
            phoneNum: "13811111111",
            gender: "男",
            memberCards: [],
            birthDate: "1990-01-01",
            enterDate:"2024-08-06",
            remark: "这是备注"
        },
        {
            id: 2,
            memberName: "李四",
            phoneNum: "13822222222",
            gender: "男",
            memberCards: [],
            birthDate: "1991-02-02",
            enterDate: "2024-07-05",
            remark: "这也是备注"
        },
    ])

    const newData = {
        7 : 2
    }

    const loseData = {
        8 : 2
    }

    const getMemberById = (id) => {
        return members.value.find(item => item.id === id);
    }

    const getMemberIdByName = (name) =>{
        return members.value.find(item => item.memberName === name).id;
    }

    const addMember = async (member) => {
        const newMember = {
            id: members.value.length + 1,
            memberName: member.memberName,
            phoneNum: member.phoneNum,
            gender: member.gender,
            memberCards: [],
            birthDate: member.birthDate,
            enterDate: getFormattedDate(),
            remark: member.remark
        }
        members.value.push(newMember);
        const day = new Date().getDate();
        newData[day] = (newData[day] || 0) + 1;
    }

    const editMember = (member) => {
        const temp = members.value.find(item => item.id === member.id);
        temp.memberName = member.memberName;
        temp.phoneNum = member.phoneNum;
        temp.gender = member.gender;
        temp.birthDate = member.birthDate;
        temp.remark = member.remark;
    }

    const deleteMember = (id) => {
        const index = members.value.findIndex(item => item.id === id);
        members.value.splice(index, 1);
        const day = new Date().getDate();
        loseData[day] = (loseData[day] || 0) + 1;
    }

    const getFormattedDate = () => {
        const date = new Date(Date.now());
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
    }

    const getNewData = () => {
        const res = []
        for (let i = 1; i <= new Date().getDate(); i++){
            res.push(newData[i] || 0)
        }
        return res
    }

    const getLoseData = () => {
        const res = []
        for (let i = 1; i <= new Date().getDate(); i++){
            res.push(loseData[i] || 0)
        }
        return res
    }

    return {members, 
        getMemberById,
        getMemberIdByName,
        getNewData,
        getLoseData,
        addMember,
        editMember,
        deleteMember,
    }
})
